<template>
    <div class="main p-4" id="paper">
        <div class="header">
            <div class="paper-title flex justify-center font-bold">
                {{ paper.name }}
                <el-button @click="exportPaper" v-if="global.exportingPaper === false" class="absolute right-4">发布上架</el-button>
            </div>
            <div class="desc flex items-center justify-end mt-2">
                <div class="flex justify-between text">
                    <div>（满分:{{ paper.fullScore }}分<span class="ml-4">时间:{{ paper.useTime }}分钟</span>）</div>
                    <div class="difficulty flex items-center">
                        <span class="mr-1">试卷难度: </span>
                        <el-icon v-for="i in difficultyArr" :key="i" class="icon"><StarFilled /></el-icon>
                        <!-- <svg v-for="i in difficultyArr" :key="i" class="ml-1 icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 48 48"><path stroke-linejoin="round" stroke-width="3" stroke="#414d62" fill="#414d62" d="m23.999 5-6.113 12.478L4 19.49l10.059 9.834L11.654 43 24 36.42 36.345 43 33.96 29.325 44 19.491l-13.809-2.013L24 5Z" data-follow-fill="#414d62" data-follow-stroke="#414d62"/></svg> -->
                        <!-- <img v-for="i in difficultyArr" :key="i" class="ml-1 icon relative top-0" :src="starSvg"> -->
                    </div>
                </div>
            </div>
        </div>
        <div class="desc">
            <TypeTopic
            v-for="(item, i) in paper.questionsTypeVos"
            :key="item.id"
            :type-topic="item"
            :i="i"
            :textByTopicType="textByTopicType"
            :showAnswer="global.showAnswer"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
import request from '@/Utils/request';
import { computed, nextTick, onMounted, reactive } from 'vue';
import { useRoute } from 'vue-router';
import TypeTopic from './Children/TypeTopic.vue';
import type { QuestionItem } from '@/Utils/type';
import { ElLoading, ElMessage } from 'element-plus';
import htmlToPdf from '@/Utils/toPdf';
import { StarFilled } from '@element-plus/icons-vue';
import { dataURLtoFile } from '@/Utils/utils';

const route = useRoute();

interface Paper {
    id: number;
    name: string;
    fullScore: number;
    useTime: number;
    difficulty: number;
    questionsTypeVos: QuestionsTypeVos[]; 
}

interface QuestionsTypeVos {
    id: number;
    type: number;
    everyoneScore: number;
    fullScore: number;
    difficulty: number;
    questionsList: QuestionItem[];
    name?: string;
}

const global = reactive({
    paper: <Paper>{
        id: 0,
        name: '',
        fullScore: 0,
        useTime: 0,
        difficulty: 0,
        questionsTypeVos: []
    },
    exportingPaper: false,
    showAnswer: false
});

const textByTopicType = {
    1: '填空题',
    2: '选择题',
    3: '计算题',
    4: '应用题',
    5: '判断题'
};

const paper = computed(() => global.paper);

const difficultyArr = computed(() => {
    const arr: any[] = [];
    let difficulty = paper.value.difficulty || 1;
    if (difficulty <= 0) difficulty = 1;
    arr.length = difficulty;
    return arr;
});

const getPaper = async () => {
    const paper = await request({
        method: 'post',
        url: '/paper/getOneById',
        contentTypeIsForm: true,
        data: {
            id: route.params.id
        },
        showLoading: {}
    });
    global.paper = paper;
};

const exportPaper = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: '发布中...',
        background: 'rgba(0, 0, 0, 0.7)',
        body: true
    });
    try {
        global.exportingPaper = true;
        global.showAnswer = false;
        await nextTick();
        const pdf: any = await htmlToPdf(global.paper.name, "paper");
        global.showAnswer = true;
        await nextTick();
        const pdfAnswer: any = await htmlToPdf(global.paper.name, "paper");
        const pdfData = await pdf.output('datauristring');
        const pdfDataAnser = await pdfAnswer.output('datauristring');
        const files = dataURLtoFile(pdfData, `${global.paper.name}.pdf`) // 将base64文件转化为流，上传oss
        const filesAnswer = dataURLtoFile(pdfDataAnser, `${global.paper.name}(含答案).pdf`) // 将base64文件转化为流，上传oss
        const formData = new FormData();
        const formDataAnswer = new FormData();
        formData.append('file', files);
        formDataAnswer.append('file', filesAnswer);
        const [ pdfRes, pdfAnswerRes ] = await Promise.allSettled([
            request({
                url: '/file/upload',
                method: 'post',
                data: formData,
                errorToast: true,
                headers: {
                    'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarytdCiBFRAtmDKmIsJ'
                },
            }),
            request({
                url: '/file/upload',
                method: 'post',
                data: formDataAnswer,
                errorToast: true,
                headers: {
                    'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarytdCiBFRAtmDKmIsJ'
                },
            }),
        ]);
        let pdfUrl = '';
        let pdfAnswerUrl = '';
        if (pdfRes.status === 'fulfilled') pdfUrl = pdfRes.value.url;
        if (pdfAnswerRes.status === 'fulfilled') pdfAnswerUrl = pdfAnswerRes.value.url;
        global.exportingPaper = false;
        await request({
            url: '/paper/online',
            method: 'post',
            contentTypeIsForm: true,
            data: {
                id: route.params.id,
                pdfUrl,
                pdfAnswerUrl
            }
        });
        loading.close();
        ElMessage({
            message: '发布成功',
            type: 'success'
        });
    } catch (error) {
        console.warn('error: ', error);
        global.exportingPaper = false;
        loading.close();
    }
};

// onActivated(() => {
//     getPaper();
// });

onMounted(() => {
    getPaper();
    if (sessionStorage.getItem("EXPORT_PAPER")) {
        sessionStorage.removeItem("EXPORT_PAPER");
        exportPaper();
    }
});
</script>

<style lang="scss" scoped>
@import "./PaperView.scss";


</style>